package com.zhx.threadcoreknowledge.threadobjectclasscommonmethod;

/**
 * @author ：zhanghaixuan
 * @date ：Created in 2019-10-03 16:01
 * 用途         ： 两个线程交替打印到100
 */
public class CountNumTo100Demo1 {

    private static CountNumTo100Demo1 self = new CountNumTo100Demo1();

    private int maxnum = 100;

    private static Object object = new Object();

    private static int count = 0;

    public static void main(String[] args) {
        Thread manThread = new Thread(self.new ManThread(self.maxnum));
        Thread girlThread = new Thread(self.new GirlThread(self.maxnum));

        girlThread.start();
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        manThread.start();
    }

    class ManThread implements Runnable {
        private int maxnum;

        public ManThread(int maxnum) {
            this.maxnum = maxnum;
        }

        @Override
        public void run() {
            while (count < maxnum) {
                synchronized (object) {
                    if((count & 1) == 1){
                        System.out.println("奇数线程打印:" + count++);
                    }
                }
            }
        }
    }

    class GirlThread implements Runnable {
        private int maxnum;

        public GirlThread(int maxnum) {
            this.maxnum = maxnum;
        }

        @Override
        public void run() {
            while (count <= maxnum) {
                synchronized (object) {
                    if((count & 1) == 0){
                        System.out.println("偶数线程打印:" + count++);
                    }
                }
            }
        }
    }
}
